var that;
Page({
  data: {
    userInfo:null,
    images: [],
    content:'',
    images_upload_success:[],//图片上传云端数组
    images_upload_success_size:0//图片上传成功的数量
  },
  onLoad: function (options) {
    that=this;
    wx.getStorage({
      key: 'userInfo',
      success(res){
        that.setData({
          userInfo:JSON.parse(res.data)
        })
      }
    })
  },
  input:function(e){
    this.setData({
      content:e.detail.value
    })
  },
  chooseimage:function(){
    wx.chooseImage({
      count: 1, 
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function (res) {
        
        if (res.tempFilePaths.length>0){
 
          //图如果满了9张，不显示加图
          if (res.tempFilePaths.length == 9){
            that.setData({
              hideAdd:1
            })
          }else{
            that.setData({
              hideAdd: 0
            })
          }
          that.setData({
            images: res.tempFilePaths
          })
        }
      }
    })  
  },
  uploadImage(index){
    wx.cloud.uploadFile({
      cloudPath:'publish'+new Date().getTime()+""+Math.floor(Math.random()+1000)+".jpg",
      filePath:that.data.images[index],//文件路径
      success:res=>{
        //get resource ID
        console.log(res.fileID)
        that.data.images_upload_success[index]=res.fileID;
        that.data.images_upload_success_size=that.data.images_upload_success_size+1;
        if( that.data.images_upload_success_size==that.data.images.length)
        {
          console.log("success:", that.data.images_upload_success)
          that.circleadd();
        }else{
          that.uploadImage(index+1);
        }
      },
      fail:err=>{
       that.currentComplete();
        wx.hideLoading()
        wx.showToast({
          icon:'none',
          title: '图片上传失败',
        })
        //handle error
      }
    })
  },
  //发布按钮事件
  send:function(){
    if(that.data.content.trim().length==0&&that.data.images.length==0){
      wx.showToast({
        icon:'none',
        title: '请发布点内容吧',
      })
      return ;
    }
    wx.showLoading({
      title: '上传数据中...',
    })
    if(that.data.images.length>0){
      that.setData({
        images_upload_success:that.data.images
      })
      that.uploadImage(0)
    }else{
      that.circleadd();
    }
  },
  circleadd(){
    var db=wx.cloud.database();
    db.collection('circle').add({
      data:{
        content:that.data.content,
        images:that.data.images_upload_success,
        time:new Date(),
        loveList:[],
        commentList:[],
        userInfo:that.data.userInfo,
      }
    }).then(res=>{
      wx.hideLoading();
      wx.showToast({
        title: '发布成功',
      })
      let pages=getCurrentPages();
      let before=pages[pages.length-2]
      before.refresh()
      wx.navigateBack({
       delta:1
      })
    }).catch(error=>{
      wx.hideLoading();
    })
  }
})